package com.ccb.sc.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccb.sc.order.service.IAppOrderRefundService;
import com.ccb.sc.order.service.IAppOrderService;
import com.ccb.sc.common.enums.AuditStatus;
import com.ccb.sc.common.modules.order.entity.Order;
import com.ccb.sc.common.modules.order.entity.OrderRefund;
import com.ccb.sc.common.modules.order.enums.DeliverStatus;
import com.ccb.sc.common.modules.order.mapper.OrderRefundMapper;
import com.ccb.sc.common.modules.payment.entity.Payment;
import com.ccb.sc.common.modules.payment.enums.PaymentStatus;
import com.ccb.sc.common.modules.payment.mapper.PaymentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 订单退款表 服务实现类
 * </p>
 *
 * @author ken
 * @since 2020-10-14
 */
@Service
public class AppOrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund> implements IAppOrderRefundService {

    private IAppOrderService orderService;
    private PaymentMapper paymentMapper;

    @Override
    public boolean refund(Long memberId, String orderId, String reason) {
        Order order = this.orderService.getById(orderId);
        Assert.isTrue(order != null && order.getMemberId().equals(memberId), "未找到订单");
        Assert.isTrue(DeliverStatus.WAIT_DELIVER.equals(order.getDeliverStatus()) , "已收货订单需申请退货，有问题请联系客服");
        Assert.isTrue(order.getPaymentStatus() == PaymentStatus.SUCCESS,"订单状态异常");
        Payment payment = this.paymentMapper.selectById(order.getTradeNo());
        OrderRefund orderRefund = new OrderRefund();
        orderRefund.setOrderId(orderId);
        orderRefund.setMemberId(memberId);
        orderRefund.setPayAmount(order.getRealAmount());
        orderRefund.setPoints(order.getUsePoints().intValue());
        orderRefund.setWalletAmount(order.getWalletDeductAmount());
        orderRefund.setReason(reason);
        orderRefund.setPaymentMethod(order.getPaymentMethod());
        orderRefund.setPaymentPluginId(payment.getPaymentPluginId());
        orderRefund.setTradeNo(order.getTradeNo());
        orderRefund.setStatus(AuditStatus.WAITAUDIT);
        return this.save(orderRefund);
    }




    @Autowired
    public void setOrderService(IAppOrderService orderService) {
        this.orderService = orderService;
    }

    @Autowired
    public void setPaymentMapper(PaymentMapper paymentMapper) {
        this.paymentMapper = paymentMapper;
    }
}
